package org.example.springboot.controller;

import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.example.springboot.common.Result;
import org.example.springboot.entity.Employee;
import org.example.springboot.mapper.EmployeeMapper;
import org.example.springboot.service.EmployService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")//给接口指定一个路径
public class EmployeeController {

    @Resource
    private EmployService employService; //引入service包的方法
    @Autowired
    private EmployeeMapper employeeMapper;

    //查询所有的数据
    /*
    get:查询操作
    post：增加操作
    put：修改操作
    delete：删除 操作
     */
    @GetMapping("/selectAll")
    public Result selectAll(){
        List<Employee> list = employService.selectAll();//然后通过service方法获取到数据
        return Result.success(list);
    }

    //根据参数查询单个数据
    // 通过注解方式查询 {id}是要查询的条件
    //这是根据路径传参
    //在浏览器中传参是：http://localhost:8080/employee/selectById/1
    @GetMapping("/selectById/{id}/{workno}")
    public Result selectById(@PathVariable Integer id,@PathVariable String workno){
        Employee employee = employService.selectById(id);
        return Result.success(employee);
    }
    //查询单个数据
    //根据url传参 可以传递多个参数
    //在浏览器中查询是：http://localhost:8080/employee/selectOne?id=1&workon = 2
    @GetMapping("/selectOne")
    public Result selectOne(@RequestParam Integer id,@RequestParam String workno){
        Employee employee = employService.selectById(id);
        return Result.success(employee);
    }

    //可以传递一个对象
    //那么该对象所有的属性都可以作为参数传递进来都可以通过?id=1传递进来
    @GetMapping("/selectList")
    public Result selectList(Employee employee){
        List<Employee> list = employService.selectList(employee);
        return Result.success(list);
    }

    //分页查询 有多少页 每一页有多少个
    /*
    分页查询：必须参数
    pageNum：当前页码
    pageSize：每页的个数
    defaultValue是给定默认值 默认只有一页，一页有十个数据
     */
    @GetMapping("/selectPage")
    public Result selectPage(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize){
        PageInfo<Employee> pageInfo = employService.selectPage(pageNum,pageSize);//返回一个分页数据
        return Result.success(pageInfo);
    }

    //增加数据
    @PostMapping("/add")
    //@RequestBody注解把前端传来的数据映射为java的对象或者数组
    public Result add(@RequestBody Employee employee){
        employService.add(employee);
        return Result.success();
    }

    //更新数据
    @PutMapping("/update")
    public Result update(@RequestBody Employee employee){
        employService.update(employee);
        return Result.success();
    }

    //删除数据
    @DeleteMapping("/deleteById/{id}")
    public Result delete(@PathVariable Integer id){
        employService.deleteById(id);
        return Result.success();
    }

}
